package org.oslims.server.service.impl;

import java.util.List;
import java.util.Set;

import net.sf.gilead.gwt.GwtConfigurationHelper;
import net.sf.gilead.gwt.PersistentRemoteService;

import org.hibernate.Session;
import org.oslims.client.service.SampleTypeService;
import org.oslims.domain.SampleType;
import org.oslims.server.dao.SampleTypeDao;
import org.oslims.server.dao.hbm.HbmSampleTypeDao;
import org.oslims.server.dao.util.HibernateUtil;

import com.google.gwt.validation.client.InvalidConstraint;
import com.google.gwt.validation.client.interfaces.IValidator;
import com.google.gwt.validation.server.ServerValidator;

public class SampleTypeServiceImpl extends PersistentRemoteService implements SampleTypeService {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4464139023786525836L;

	SampleTypeDao sampleTypeDao;

	IValidator<SampleType> sampleTypeValidator = new ServerValidator<SampleType>();

	public SampleTypeServiceImpl() {
		sampleTypeDao = new HbmSampleTypeDao();

		net.sf.gilead.core.hibernate.HibernateUtil hibernateUtil = new net.sf.gilead.core.hibernate.HibernateUtil(HibernateUtil.getSessionFactory());
		setBeanManager(GwtConfigurationHelper.initGwtStatelessBeanManager(hibernateUtil));
	}

	@Override
	public List<SampleType> getAllSampleType() {
		Session session = HibernateUtil.getSession();
		sampleTypeDao.setSession(session);

		List<SampleType> result = sampleTypeDao.findAllWithAnalysis();

		session.close();

		return result;
	}

	@Override
	public void saveOrUpdateSampleType(SampleType sampleType) {

		Set<InvalidConstraint<SampleType>> violations = sampleTypeValidator.validate(sampleType);

		if (violations.size() == 0) { // Only process the entity if valid!!!
			Session session = HibernateUtil.getSession();
			session.beginTransaction();
			try {
				sampleTypeDao.setSession(session);
				sampleTypeDao.makePersistent(sampleType);
				session.getTransaction().commit();
			} catch (RuntimeException e) {
				session.getTransaction().rollback();
				throw e;
			} finally {
				session.close();
			}
		}
	}

	@Override
	public List<SampleType> getSampleTypes(int start, int length, String sortBy, boolean desc) {
		Session session = HibernateUtil.getSession();
		sampleTypeDao.setSession(session);

		List<SampleType> result = sampleTypeDao.findAllWithAnalysis(start, length, sortBy, desc);

		session.close();

		return result;
	}

	@Override
	public Integer getSampleTypeCount() {
		Session session = HibernateUtil.getSession();
		sampleTypeDao.setSession(session);

		Integer result = sampleTypeDao.getEntityCount();

		session.close();

		return result;
	}

}
